package ui;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.swing.AbstractListModel;

import application.TruePredicate;

import com.google.common.base.Predicate;

import workers.ClientListWorker;

@SuppressWarnings("serial")
public class SearchResultsListModel extends AbstractListModel implements PropertyChangeListener {

	List<Object> elements = Collections.synchronizedList(new ArrayList<Object>());
	List<Object> filteredElements = new ArrayList<Object>();
	
	Predicate<Object> predicate;
	public SearchResultsListModel() {
		predicate = null;
	}
	@Override
	public Object getElementAt(int index) {
		return filteredElements.get(index);
	}

	@Override
	public int getSize() {
		return filteredElements.size();
	}

	@Override
	public void propertyChange(PropertyChangeEvent evt) {
		if( evt.getSource() instanceof ClientListWorker){
			int initialSize = filteredElements.size();
			if( evt.getPropertyName().equals( ClientListWorker.PROPERTY_RESULT_LIST ) ){
				List<Object> results = ((ClientListWorker) evt.getSource()).getList();
				elements.addAll(results);
				for (Object object : results) {
					if( predicate.apply(object)){
						filteredElements.add(object);
					}
				}
				fireIntervalAdded(this, initialSize, filteredElements.size());
			}
		}
	}
	
	public void setPredicate(Predicate<Object> p){
		predicate = p;
		if( predicate == null ){
			predicate = new TruePredicate();
		}
		
		filteredElements.clear();
		for (Object object : elements) {
			if( predicate.apply(object)){
				filteredElements.add(object);
			}
		}
		fireIntervalAdded(this, 0, filteredElements.size());
	}
	
	public void clear(){
		filteredElements.clear();
		int size = elements.size();
		elements.clear();
		fireIntervalRemoved(this, 0, size);
	}
}